package com.jr.controller;

import com.jr.mapper.BookingMapper;
import com.jr.pojo.Booking;
import com.jr.pojo.Notification;
import com.jr.service.NotificationService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/api/bookings")
@CrossOrigin(origins = "*")
public class BookingController {

    @Autowired
    private BookingMapper bookingMapper;
    
    @Autowired
    private NotificationService notificationService;

    @PostMapping("/create")
    @ResponseBody
    public Map<String, Object> createBooking(@RequestBody Map<String, Object> bookingData) {
        Map<String, Object> result = new HashMap<>();
        
        try {
            // 创建预约对象
            Booking booking = new Booking();
            booking.setUserId((Integer) bookingData.get("userId"));
            booking.setProviderId((Integer) bookingData.get("providerId"));
            booking.setServiceTypeId((Integer) bookingData.get("serviceTypeId"));
            booking.setPetId((Integer) bookingData.get("petId"));
            
            // 处理日期
            String startDateStr = (String) bookingData.get("startDate");
            String endDateStr = (String) bookingData.get("endDate");
            booking.setStartDate(LocalDateTime.parse(startDateStr + "T00:00:00"));
            booking.setEndDate(LocalDateTime.parse(endDateStr + "T23:59:59"));
            
            booking.setSpecialRequests((String) bookingData.get("specialRequests"));
            booking.setTotalPrice(new java.math.BigDecimal(bookingData.get("totalPrice").toString()));
            booking.setStatus((String) bookingData.get("status"));
            booking.setCreatedAt(LocalDateTime.now());
            booking.setUpdatedAt(LocalDateTime.now());
            
            // 插入数据库
            int insertResult = bookingMapper.insertBooking(booking);
            
            if (insertResult > 0) {
                // 创建预约成功通知
                createBookingNotification(booking);
                
                result.put("success", true);
                result.put("message", "预约创建成功");
                result.put("bookingId", booking.getBookingId());
                result.put("booking", booking);
            } else {
                result.put("success", false);
                result.put("message", "预约创建失败");
            }
            
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "预约创建失败: " + e.getMessage());
            System.err.println("预约创建失败: " + e.getMessage());
        }
        
        return result;
    }

    @GetMapping("/user/{userId}")
    @ResponseBody
    public Map<String, Object> getUserBookings(@PathVariable Integer userId) {
        Map<String, Object> result = new HashMap<>();
        
        try {
            var bookings = bookingMapper.selectByUserId(userId);
            result.put("success", true);
            result.put("bookings", bookings);
            result.put("count", bookings.size());
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "获取预约列表失败: " + e.getMessage());
        }
        
        return result;
    }
    
    // 创建预约通知
    private void createBookingNotification(Booking booking) {
        try {
            Notification notification = new Notification();
            notification.setUserId(booking.getUserId());
            notification.setType("booking_created");
            notification.setTitle("预约提交成功");
            notification.setContent(String.format(
                "您的预约已成功提交，预约编号：BK%06d，服务时间：%s 至 %s，总费用：¥%.2f。我们会尽快与您联系确认详情。",
                booking.getBookingId(),
                booking.getStartDate().toLocalDate(),
                booking.getEndDate().toLocalDate(),
                booking.getTotalPrice()
            ));
            notification.setIsRead(false);
            notification.setCreatedAt(LocalDateTime.now());
            
            // 发送通知
            notificationService.sendNotification(notification);
            
            System.out.println("预约通知创建成功 - 用户ID: " + booking.getUserId() + ", 预约ID: " + booking.getBookingId());
            
        } catch (Exception e) {
            System.err.println("创建预约通知失败: " + e.getMessage());
        }
    }
}
